﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using XSTDZ.ERP.Infrastructure;
using System.Text;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.WebApp.Models.Extension;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Application.DataContracts;
namespace XSTDZ.ERP.WebApp.Controllers
{
    /// <summary>
    /// 数据库备份控制器
    /// </summary>
    public class DbController : Controller
    {
        private readonly IRefeService refeServiceImpl = ServiceLocator.Instance.GetService<IRefeService>();
        //
        // GET: /Db/
        //列表显示文件
        [NoAuthorizated("Index")]
        public ActionResult Index()
        {
            //var dir = this.HttpContext.Server.MapPath(SystemConfig.DataBaseBackupName);
            //DbBackupDirNotExistsCreate(dir);
            //var str = GetFileInfoFromDir(dir);
            //ViewBag.dataJson = str;
            return View();
        }
        [NoAuthorizated("Edit")]
        public ActionResult Edit()
        {
            var backUpDate = refeServiceImpl.GetDataBackDto();
            CreateDropdonelist(backUpDate.BackCount);
            return View(backUpDate);
        }
        [NoAuthorizated("Edit")]
        [HttpPost]
        public ActionResult Edit(DataBackDto dataBack)
        {
            refeServiceImpl.DataBaseBackUp(dataBack);
            ViewBag.PostState = 9;
            CreateDropdonelist(dataBack.BackCount);
            return View(dataBack);
        }
        [NoAuthorizated("GetDataOfJSON")]
        public ActionResult GetDataOfJSON()
        {
            var dir = this.HttpContext.Server.MapPath(SystemConfig.DataBaseBackupName);
            DbBackupDirNotExistsCreate(dir);
            var str = GetFileInfoFromDir(dir);
            return Content(str);
        }
        #region 文件流操作文件及目录
        /// <summary>
        /// 数据库目录(不存在就创建)
        /// </summary>
        private void DbBackupDirNotExistsCreate(string dir)
        {
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }
        /// <summary>
        /// 获取目录下的所有文件信息
        /// </summary>
        private string GetFileInfoFromDir(string dir)
        {
            string fileLink = @"../Db/{0}/{1}";// "<a href='../Db/{0}/{1}' title='{1}' alt='{1}' target='_blank'>{1}</a>";
            StringBuilder sb = new StringBuilder();
            IList<FileModel> lst = new List<FileModel>();
            sb.Append("{ Rows: [");
            var files = Directory.GetFiles(dir);
            int len = files == null ? 0 : files.Length;
            if (len > 0)
            {
                for (int i = 0; i < files.Length; i++)
                {
                    var fileName = files[i].ToString().GetFileNameFormDir();
                    // sb.Append("{\"rownum1\":\"" + (i + 1).ToString() + "\",\"filename\":\"" + string.Format(fileLink, SystemConfig.DataBaseBackupName, fileName) + "\",\"createdate\":\"" + System.IO.File.GetLastWriteTime(files[i].ToString()) + "\"},");
                    lst.Add(new FileModel
                    {
                        URL = string.Format(fileLink, SystemConfig.DataBaseBackupName, fileName),
                        FileName = fileName,
                        CreateDate = DateTime.Parse(System.IO.File.GetLastWriteTime(files[i].ToString()).ToString("yyyy-MM-dd hh:mm:ss"))
                    });
                }
            }
            //  sb.Append("], Total: " + len + " };");
            return GetLists(lst);
        }

        /// <summary>
        ///  用户信息 [返回JSONResult]
        /// </summary>
        public string GetLists(IList<FileModel> lst)
        {
            var target = Newtonsoft.Json.JsonConvert.SerializeObject(lst);
            return target = "{\"Rows\":" + target + ",\"Total\":\"" + lst.Count + "\"}";

        }


        #endregion

        #region 备份份数下拉框
        private void CreateDropdonelist(int backCount)
        {
            var list = new List<SelectListItem>();
            for (int i = 1; i < 7; i++)
            {
                var item = new SelectListItem();
                item.Text = i.ToString();
                item.Value = i.ToString();
                if (backCount == i)
                {
                    item.Selected = true;
                }
                list.Add(item);
            }
            ViewData["BackCount"] = list;
           // ViewBag.backcount = list;
        }
        #endregion
    }

    public class FileModel
    {
        public string URL { get; set; }
        public string FileName { get; set; }
        public DateTime CreateDate { get; set; }
    }
}
